package com.spzx.product.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.redis.cache.GuiguCache;
import com.spzx.product.api.domain.*;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedisTemplate redisTemplate;

    //分页列表
    @Override
    public List<Product> getProductList(Product product) {
        return productMapper.getProductList(product);
    }

    //新增商品
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addProduct(Product product) {
        //保存SPU
        productMapper.insert(product);
        Long productId = product.getId();

        List<ProductSku> productSkuList = product.getProductSkuList();
        int size = productSkuList.size();
        for (int i = 0; i < size; i++) {
            //保存多个SKU
            ProductSku productSku = productSkuList.get(i);
            productSku.setSkuCode(productId + "_" + i);
            productSku.setSkuName(product.getName() + " " + productSku.getSkuSpec());
            productSku.setProductId(productId);
            productSku.setStatus(0);
            productSkuMapper.insert(productSku);

            //保存库存
            SkuStock skuStock = new SkuStock();
            skuStock.setSkuId(productSku.getId());
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setLockNum(0);
            skuStock.setAvailableNum(productSku.getStockNum());
            skuStock.setSaleNum(0);
            skuStock.setStatus(0);
            skuStockMapper.insert(skuStock);

        }

        //保存详情图片
        ProductDetails productDetails = new ProductDetails();
        productDetails.setProductId(productId);
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetailsMapper.insert(productDetails);

        return 1;
    }

    //获取商品详细信息

    @Override
    public Product getProductById(Long id) {
        //查询商品
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new ServiceException("数据不存在!");
        }

        //商品SKU列表
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));

        //根据6个sku可以获取6个skuId,可以获取6个SkuStock对象；
        //获取每一个skuStock库存值，封装在sku对象中。
        List<Long> skuIdList = productSkuList.stream().map(ProductSku::getId).toList();

        //查询库存
        List<SkuStock> skuStockList = skuStockMapper.selectList(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, skuIdList));
        Map<Long, Integer> skuIdToTotalNumMap = skuStockList.stream().collect(Collectors.toMap(SkuStock::getSkuId, SkuStock::getTotalNum));

        for (ProductSku productSku : productSkuList) {
            productSku.setStockNum(skuIdToTotalNumMap.get(productSku.getId()));
        }

        product.setProductSkuList(productSkuList);

        //查询详情图片
        ProductDetails productDetails = productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
        product.setDetailsImageUrlList(Arrays.asList(productDetails.getImageUrls().split(",")));
        return product;
    }

    //修改商品
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateProduct(Product product) {
        //修改SPU
        productMapper.updateById(product);

        List<ProductSku> productSkuList = product.getProductSkuList();
        for (ProductSku productSku : productSkuList) {
            //修改多个SKU
            productSku.setSkuName(product.getName() + " " + productSku.getSkuSpec());
            productSkuMapper.updateById(productSku);

            //修改多个SkuStock
            SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, product.getId()));
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setAvailableNum(productSku.getStockNum() - skuStock.getLockNum());
            skuStockMapper.updateById(skuStock);
        }

        //修改详情图片信息
        ProductDetails productDetails = new ProductDetails();
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetailsMapper.update(productDetails, new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId()));

        return 1;
    }

    //删除商品
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteProductByIds(Long[] ids) {
        //删除Product
        productMapper.deleteBatchIds(Arrays.asList(ids));

        //删除ProductSku
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, ids));
        List<Long> skuIdList = productSkuList.stream().map(ProductSku::getId).toList();
        productSkuMapper.deleteBatchIds(skuIdList);

        //删除SkuStock
        skuStockMapper.delete(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, skuIdList));

        //删除ProductDetails
        productDetailsMapper.delete(new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId, ids));
        return 1;
    }

    //商品审核
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if (auditStatus == 1) {
            product.setAuditStatus(1);
            product.setAuditMessage("审核通过");
        } else {
            product.setAuditStatus(-1);
            product.setAuditMessage("审核不通过");
        }
        productMapper.updateById(product);
    }

    //更新上下架状态
    /*@Override
    public void updateStatus(Long id, Integer status) {
        Product product = new Product();
        product.setId(id);
        if (status==1){
            product.setStatus(1);
        }else {
            product.setStatus(-1);
        }
        productMapper.updateById(product);
    }*/


    //商品上下架时将数据添加到布隆过滤器中
    @Override
    public void updateStatus(Long id, Integer status) {
        Product product = new Product();
        product.setId(id);
        if (status == 1) {
            product.setStatus(1);

            //sku加入布隆过滤器
            RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("sku:bloom:filter");
            List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
            productSkuList.forEach(item -> {
                bloomFilter.add(item.getId());
            });
        } else {
            product.setStatus(-1);
        }
        productMapper.updateById(product);
    }

    //=========================前台页面接口=========================

    //获取销量好的sku
    @Override
    public List<ProductSku> getTopSale() {
        return productSkuMapper.selectTopSale();
    }

    @Override
    public List<ProductSku> getProductSkuList(SkuQuery skuQuery) {
        return productSkuMapper.getProductSkuList(skuQuery);
    }

    //====================商品详情六个接口=======================

    @Override
    public ProductSku getProductSku(Long skuId) {
        return productSkuMapper.selectById(skuId);
    }

    @GuiguCache(prefix = "product:")
    @Override
    public Product getProductInfo(Long id) {
        return productMapper.selectById(id);
    }

    @Override
    public SkuPrice getProductSkuPrice(Long skuId) {
        ProductSku productSku = productSkuMapper.selectById(skuId);
        SkuPrice skuPrice = new SkuPrice();
        skuPrice.setSkuId(skuId);
        skuPrice.setSalePrice(productSku.getSalePrice());
        skuPrice.setMarketPrice(productSku.getMarketPrice());
        return skuPrice;
    }

    @GuiguCache(prefix = "productDetails:")
    @Override
    public ProductDetails getProductDetails(Long productId) {
        ProductDetails productDetails = productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, productId));
        return productDetails;
    }

    @GuiguCache(prefix = "skuSpecValue:")
    @Override
    public Map<String, Long> getSkuSpecInfo(Long productId) {
        Map<String, Long> map = new HashMap<>();
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, productId));
        for (ProductSku productSku : productSkuList) {
            map.put(productSku.getSkuSpec(), productSku.getId());
        }
        return map;
    }

    @Override
    public SkuStockVo getSkuStock(Long skuId) {
        SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, skuId));
        SkuStockVo skuStockVo = new SkuStockVo();
        skuStockVo.setSkuId(skuId);
        skuStockVo.setSaleNum(skuStock.getSaleNum());
        skuStockVo.setAvailableNum(skuStock.getAvailableNum());
        return skuStockVo;
    }


    //======================END================================

    //批量获取商品sku最新价格信息
    @Override
    public List<SkuPrice> getSkuPriceList(List<Long> skuIdList) {
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getId, skuIdList).select(ProductSku::getId, ProductSku::getSalePrice));
        return productSkuList.stream().map(item -> {
            SkuPrice skuPrice = new SkuPrice();
            skuPrice.setSkuId(item.getId());
            skuPrice.setSalePrice(item.getSalePrice());
            return skuPrice;
        }).collect(Collectors.toList());
    }

    //检查与锁定库存
    @Transactional
    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        String dataKey = "sku:lock:data:" + orderNo; //用于存储锁定库存数据
        String lockKey = "sku:checkAndLock:lock:" + orderNo;

        //防止重复请求
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(lockKey, orderNo, 1, TimeUnit.MINUTES);
        if (!ifAbsent) {
            if (redisTemplate.hasKey(dataKey)) {
                return " ";
            }
        } else {
            return "请勿重复提交";
        }

        //遍历所有商品，对每一个商品进行库存检查(增加行锁 for update,不允许别的事务进行数据操作。)
        for (SkuLockVo skuLockVo : skuLockVoList) {
            SkuStock skuStock = skuStockMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if (skuStock == null) {
                skuLockVo.setIsHaveStock(false);
            } else {
                skuLockVo.setIsHaveStock(true);
            }
        }

        //判断是否存在库存不够的商品，如果存在库存不够的商品情况，那么，返回特定字符串消息即可；
        if (skuLockVoList.stream().anyMatch(skuLockVo -> !skuLockVo.getIsHaveStock())) {
            StringBuffer stringBuffer = new StringBuffer();
            List<SkuLockVo> noCheckSkulist = skuLockVoList.stream().filter(skuLockVo -> !skuLockVo.getIsHaveStock()).toList();
            for (SkuLockVo skuLockVo : noCheckSkulist) {
                stringBuffer.append("商品：[" + skuLockVo.getSkuId() + "]库存不足;");
                redisTemplate.delete(lockKey);
                return stringBuffer.toString();
            }
        } else {
            //如果所有库存检查没问题，商品库存都够。那么才会锁定库存，不让别人买这个商品。
            for (SkuLockVo skuLockVo : skuLockVoList) {
                int row = skuStockMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
                if (row == 0) {
                    redisTemplate.delete(lockKey);
                    throw new ServiceException("锁库存失败");
                }
            }
        }
        //把锁定库存信息保存到redis中，不设置过期时间，等着  解锁库存(取消订单)  或   减库存(支付成功)
        redisTemplate.opsForValue().set(dataKey, skuLockVoList);
        return " ";
    }

    //解锁库存
    @Transactional
    @Override
    public void unlock(String orderNo) {
        String dataKey = "sku:lock:data:" + orderNo; //用于存储锁定库存数据
        String lockKey = "sku:unlock:lock:" + orderNo;

        //防止重复请求
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(lockKey, orderNo, 1, TimeUnit.MINUTES);
        if (!ifAbsent) {
            if (redisTemplate.hasKey(dataKey)) ;
            return;
        }

        // 获取锁定库存的缓存信息
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>) redisTemplate.opsForValue().get(dataKey);
        if (CollectionUtils.isEmpty(skuLockVoList)) {
            redisTemplate.delete(lockKey);
            return;
        }
        //数据在, 解锁库存
        for (SkuLockVo skuLockVo : skuLockVoList) {
            int row = skuStockMapper.unlock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if (row == 0) {
                redisTemplate.delete(lockKey);
                throw new ServiceException("解锁失败");
            }
        }
        //活干完后删除缓存数据; 避免重复解锁 或者 重复减库存
        redisTemplate.delete(dataKey);
    }


    //扣减库存
    @Transactional
    @Override
    public void minus(String orderNo) {
        String dataKey = "sku:lock:data:" + orderNo; //用于存储锁定库存数据
        String lockKey = "sku:minus:lock:" + orderNo;

        //防止重复请求
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(lockKey, orderNo, 1, TimeUnit.MINUTES);
        if (!ifAbsent) {
            if (redisTemplate.hasKey(dataKey)) ;
            return;
        }

   List<SkuLockVo> skuLockVoList=(List<SkuLockVo>)  redisTemplate.opsForValue().get(dataKey);
        if (CollectionUtils.isEmpty(skuLockVoList)){
            redisTemplate.delete(lockKey);
            return;
        }
        for (SkuLockVo skuLockVo : skuLockVoList) {
        int row=    skuStockMapper.minus(skuLockVo.getSkuId(),skuLockVo.getSkuNum());
        if (row == 0){
            redisTemplate.delete(lockKey);
            throw new ServiceException("减库存失败");
        }
        }
        redisTemplate.delete(dataKey);
    }
}